package com.mingqi.enetconnected.net.webview;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.Response;
import com.mingqi.enetconnected.R;
import com.mingqi.enetconnected.net.callback.JsonCallback;
import com.mingqi.enetconnected.primary.MainActivity;
import com.mingqi.enetconnected.util.ACache;
import com.mingqi.enetconnected.util.NormalKey;
import com.mingqi.enetconnected.util.log.Log2FileUtils;
import com.mingqi.enetconnected.view.Dialog.LoginDialog;
import com.netease.nim.uikit.support.permission.MPermission;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionDenied;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionGranted;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionNeverAskAgain;
import com.tencent.sonic.sdk.SonicConfig;
import com.tencent.sonic.sdk.SonicConstants;
import com.tencent.sonic.sdk.SonicEngine;
import com.tencent.sonic.sdk.SonicSession;
import com.tencent.sonic.sdk.SonicSessionConfig;
import com.tencent.sonic.sdk.SonicSessionConnection;

import org.apache.lucene.portmobile.charset.StandardCharsets;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WelcomeActivity extends AppCompatActivity {

    public final static String CODE_URL = "http://vcc.hbasesoft.com:8062/oauth/authorize?client_id=340f2e51fb3b41f699d314548cb25be8&scope=read%20write&response_type=code&redirect_uri=http%3A%2F%2Fsu0105.hbasesoft.com%3A8060%2Fuser%2Flogin";

    public final static String PARAM_URL = "param_url";

    public final static String PARAM_MODE = "param_mode";
    public final static String PARAM_NOTE = "PARAM_NOTE";
    private SonicSession sonicSession;

    private WebView webView;
    private LoginDialog mLoginDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        requestBasicPermission();
        Intent intent = this.getIntent();
        String note = intent.getStringExtra(PARAM_NOTE);
        if (!TextUtils.isEmpty(note)) {
            mLoginDialog = new LoginDialog(this);
            mLoginDialog.setCanceledOnTouchOutside(true);
            mLoginDialog.setCancelable(true);
            mLoginDialog.show();
            mLoginDialog.setHintMessage(note);

        }
        if (!SonicEngine.isGetInstanceAllowed()) {
            SonicEngine.createInstance(new SonicRuntimeImpl(getApplication()), new SonicConfig.Builder().build());
        }
        SonicSessionClientImpl sonicSessionClient = null;
        SonicSessionConfig.Builder sessionConfigBuilder = new SonicSessionConfig.Builder();
        sessionConfigBuilder.setSupportLocalServer(true);
        sonicSession = SonicEngine.getInstance().createSession(CODE_URL, sessionConfigBuilder.build());
        if (null != sonicSession) {
            sonicSession.bindClient(sonicSessionClient = new SonicSessionClientImpl());
        }
        setContentView(R.layout.activity_browser);


        // init webview
        webView = (WebView) findViewById(R.id.webview);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (sonicSession != null) {
                    sonicSession.getSessionClient().pageFinish(url);
                }
                Log2FileUtils.e("onPageFinished:" + url);
            }

            @TargetApi(21)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return shouldInterceptRequest(view, request.getUrl().toString());
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (sonicSession != null) {
                    return (WebResourceResponse) sonicSession.getSessionClient().requestResource(url);
                }
                Log2FileUtils.e("shouldInterceptRequest:" + url);
                return null;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log2FileUtils.e(url);
                // 判断url链接中是否含有某个字段，如果有就执行指定的跳转（不执行跳转url链接），如果没有就加载url链接
                if (url.contains("code=")) {

                    String[] codes = url.split("code=");
                    String code = "";
                    if (codes.length == 2) {
                        code = codes[1];
                    }

                    String urls = "http://vcc.hbasesoft.com:8060/v1/oauth/token?seq=1535537009145&client_id=340f2e51fb3b41f699d314548cb25be8&code=" +
                            code +
                            "&grant_type=authorization_code&scope=read%20write&redirect_uri=http%3a%2f%2fsu0105.hbasesoft.com%3a8060%2fuser%2flogin&refresh_token=";
                    Log2FileUtils.e(urls);
                    OkGo.<JSONObject>post(urls).tag(WelcomeActivity.this).execute(new JsonCallback<JSONObject>() {
                        @Override
                        public void onSuccess(Response<JSONObject> response) {

                            Log2FileUtils.e(response.body().toString());
                            if (response.isSuccessful() && response.body() != null) {
                                JSONObject json = response.body();
                                String token = json.optString("value");
                                int expiresIn = json.optInt("expiresIn");
                                ACache aCache = ACache.get(WelcomeActivity.this);
                                if (aCache.getAsString(NormalKey.TOKEN) == null) {//过期再放
                                    HttpHeaders httpHeaders = new HttpHeaders(NormalKey.TOKEN, token);
                                    OkGo.getInstance().addCommonHeaders(httpHeaders);
                                    aCache.put(NormalKey.TOKEN, token, expiresIn);
                                    aCache.put(NormalKey.EXPIRESIN, expiresIn);
                                }
                                Intent i = new Intent(WelcomeActivity.this, MainActivity.class);
                                startActivity(i);
                                finish();
                            } else {
                                Log2FileUtils.e(response.getException());
                                webView.clearCache(true);
                                Intent i = new Intent(WelcomeActivity.this, WelcomeActivity.class);
                                i.putExtra(PARAM_NOTE, response.getException());
                                startActivity(i);
                                finish();
                            }
                        }

                        @Override
                        public void onError(Response<JSONObject> response) {
                            Log2FileUtils.e("onError" + response.getException());
                            super.onError(response);
                            webView.clearCache(true);

                            Intent i = new Intent(WelcomeActivity.this, WelcomeActivity.class);
                            i.putExtra(PARAM_NOTE, response.getException());
                            startActivity(i);
                            finish();

                        }
                    });


                    return true;
                }
                return false;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                Log2FileUtils.e("onReceivedError:");
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                Log2FileUtils.e("onReceivedError:" + description);
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                Log2FileUtils.e("onReceivedHttpError");
                super.onReceivedHttpError(view, request, errorResponse);
                Intent i = new Intent(WelcomeActivity.this, WelcomeActivity.class);
                i.putExtra(PARAM_NOTE, "登录异常");
                startActivity(i);
                finish();
            }
        });

        WebSettings webSettings = webView.getSettings();

        // add java script interface
        // note:if api level lower than 17(android 4.2), addJavascriptInterface has security
        // issue, please use x5 or see https://developer.android.com/reference/android/webkit/
        // WebView.html#addJavascriptInterface(java.lang.Object, java.lang.String)
        webSettings.setJavaScriptEnabled(true);
        // webSettings.setCacheMode();
        webView.removeJavascriptInterface("searchBoxJavaBridge_");
        intent.putExtra(SonicJavaScriptInterface.PARAM_LOAD_URL_TIME, System.currentTimeMillis());
        webView.addJavascriptInterface(new SonicJavaScriptInterface(sonicSessionClient, intent), "sonic");

        // init webview settings
        webSettings.setAllowContentAccess(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);


        // webview is ready now, just tell session client to bind
        if (sonicSessionClient != null) {
            sonicSessionClient.bindWebView(webView);
            sonicSessionClient.clientReady();
        } else { // default mode
            webView.loadUrl(CODE_URL);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    public String getString(InputStream inputStream) {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        String str = null;
        try {
            while ((length = inputStream.read(buffer)) != -1) {
                result.write(buffer, 0, length);
            }


            str = result.toString(StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }

    @Override
    protected void onDestroy() {
        if (null != sonicSession) {
            sonicSession.destroy();
            sonicSession = null;
        }
        super.onDestroy();
    }


    private static class OfflinePkgSessionConnection extends SonicSessionConnection {

        private final WeakReference<Context> context;

        public OfflinePkgSessionConnection(Context context, SonicSession session, Intent intent) {
            super(session, intent);
            this.context = new WeakReference<Context>(context);
        }

        @Override
        protected int internalConnect() {
            Context ctx = context.get();
            if (null != ctx) {
                try {
                    InputStream offlineHtmlInputStream = ctx.getAssets().open("sonic-demo-index.html");
                    responseStream = new BufferedInputStream(offlineHtmlInputStream);
                    return SonicConstants.ERROR_CODE_SUCCESS;
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
            return SonicConstants.ERROR_CODE_UNKNOWN;
        }

        @Override
        protected BufferedInputStream internalGetResponseStream() {
            return responseStream;
        }

        @Override
        public void disconnect() {
            if (null != responseStream) {
                try {
                    responseStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public int getResponseCode() {
            return 200;
        }

        @Override
        public Map<String, List<String>> getResponseHeaderFields() {
            return new HashMap<>(0);
        }

        @Override
        public String getResponseHeaderField(String key) {
            return "";
        }
    }

    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA
    };
    private final int BASIC_PERMISSION_REQUEST_CODE = 110;
    private final int WRITE_SETTINGS_PERMISSION_REQUEST_CODE = 1545;

    private void requestBasicPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            MPermission.with(WelcomeActivity.this)
                    .setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                    .permissions(BASIC_PERMISSIONS)
                    .request();
            if (!Settings.System.canWrite(this)) {
                Intent goToSettings = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
                goToSettings.setData(Uri.parse("package:" + this.getPackageName()));
                //  startActivityForResult(goToSettings,WRITE_SETTINGS_PERMISSION_REQUEST_CODE);
                startActivity(goToSettings);
            }

        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {

        Log.d("--TAG--", "LoginActivity onBasicPermissionSuccess()" + "授权成功");
    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionFailed() {
        Log.d("--TAG--", "LoginActivity onBasicPermissionFailed()" + "授权失败");
    }
}
